package cn.ac.cintcm.webapp.controller;

import java.util.Date;
import java.util.Locale;

import javax.persistence.EntityExistsException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.security.AccessDeniedException;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;

import cn.ac.cintcm.model.Therapy;
import cn.ac.cintcm.model.User;
import cn.ac.cintcm.service.TherapyManager;
import cn.ac.cintcm.service.UserExistsException;
import cn.ac.cintcm.service.UserManager;
import cn.ac.cintcm.util.AuthorityUtil;

public class TherapyFormController extends BaseFormController {
    private TherapyManager therapyManager = null;
	private UserManager um;
	
	private AuthorityUtil authorityUtil = null;
	
    public void setAuthorityUtil(AuthorityUtil authorityUtil) {
    	this.authorityUtil = authorityUtil;
    }
    
    public void setTherapyManager(TherapyManager therapyManager) {
        this.therapyManager = therapyManager;
    }
    
	public void setUserManager(UserManager um) {
		this.um = um;
	}

    public TherapyFormController() {
        setCommandClass(Therapy.class);
        setCommandName("therapy");
    }

    protected Object formBackingObject(HttpServletRequest request)
    throws Exception {
        String id = request.getParameter("id");
        String patient= request.getParameter("patient.id");
        String parentId= request.getParameter("pid");
        if (StringUtils.isNotBlank(patient) && !authorityUtil.hasPrivilegeById(request, null, patient)) {
        	 throw new AccessDeniedException("You do not have permission to modify other users.");
        }
        
        //Edit a therapy
        if (!StringUtils.isBlank(id)) {
        	log.debug("Editing a theropy");
            Therapy therapy = therapyManager.get(new Long(id));
            if (therapy != null && 
            		therapy.getDoctor().getUsername().equals(request.getRemoteUser())) {
            	return therapy;
            } else {
            	throw new AccessDeniedException("You do not have permission to modify.");
            }
        }
        //New therapy
        Therapy therapy = new Therapy();
        //start a new therapy
        if (patient != null && !patient.trim().equals("")) {
        	User u = um.getUser(patient);
        	therapy.setPatient(u);
        }
        //advance a therapy
        if (!StringUtils.isBlank(parentId)) {
        	Long pid = new Long(parentId);
        	therapy = therapyManager.get(pid);
        	if (therapy != null) {
        		therapy.setId(null);
        	}
        	if (therapy.getPid()==0) {
        		therapy.setPid(pid);
        	}
        }
        therapy.setTdate(new Date());
        return therapy;
    }

    public ModelAndView onSubmit(HttpServletRequest request,
                                 HttpServletResponse response, Object command,
                                 BindException errors)
    throws Exception {
        log.debug("entering 'onSubmit' method...");
        
        Therapy therapy = (Therapy) command;
        if (therapy.getPid()==null) {
        	therapy.setPid(0L);
        }
        boolean isNew = (therapy.getId() == null);
        log.debug("is new therapy: + " + isNew);
        
        String success = "redirect:patient.html?u=" + therapy.getPatient().getId();
        Locale locale = request.getLocale();
        User doctor = um.getUserByUsername(request.getRemoteUser());
        
        if (request.getParameter("delete") != null) {
        	therapyManager.remove(therapy.getId());
            saveMessage(request, getText("therapy.deleted", therapy.getPatient().getName()+"", locale));
        } else {
        	Date date = therapy.getTdate();
        	if (date == null) {
        		therapy.setTdate(new Date());
        	}
        	therapy.setDoctor(doctor);
			therapyManager.save(therapy);
			String key = (isNew) ? "therapy.added" : "therapy.updated";
			saveMessage(request, getText(key, therapy.getPatient().getName()+"", locale));

         }

        return new ModelAndView(success);
    }
}